package com.calt.plm.basic.core.factory;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

import javax.sql.DataSource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.JdbcUtils;

import com.calt.plm.basic.core.model.ActionProp;

/**
 * <p>类的简单描述</p>
 *
 * @author wuchao Create on 2022/9/22
 * @version 1.0
 */
public class SqlEngine
{
	private static String[] TYPE = new String[]
	{ "TABLE" };

	public void createTable(String tableName, DataSource dataSource, List<ActionProp> props)
	{
		Connection connection = null;
		ResultSet resultSet = null;
		try
		{
			connection = DataSourceUtils.getConnection(dataSource);
			DatabaseMetaData metaData = connection.getMetaData();
			resultSet = metaData.getTables(null, metaData.getUserName(), tableName.toUpperCase(Locale.ENGLISH), TYPE);
			while (resultSet.next())
			{
				return;
			}
		}
		catch (SQLException e)
		{
			throw new RuntimeException(e);
		}
		finally
		{
			JdbcUtils.closeResultSet(resultSet);
			DataSourceUtils.releaseConnection(connection, dataSource);
		}
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		String sql = this.initCreateSql(tableName, props);
		jdbcTemplate.execute(sql);
		List<String> indexSqlList = this.initCreateIndexSql(tableName, props);
		if(CollectionUtils.isEmpty(indexSqlList))
		{
			return;
		}
		for (String indexSql : indexSqlList)
		{
			jdbcTemplate.execute(indexSql);
		}
	}

	private String initCreateSql(String tableName, List<ActionProp> props)
	{
		StringBuffer createTableBuffer = new StringBuffer();
		createTableBuffer.append("CREATE TABLE ").append(tableName).append("(");
		props.stream().forEach(prop -> {
			createTableBuffer.append(prop.buildProp(prop));
		});
		createTableBuffer.delete(createTableBuffer.lastIndexOf(","), createTableBuffer.length());
		createTableBuffer.append(")");
		return createTableBuffer.toString();
	}

	private List<String> initCreateIndexSql(String tableName, List<ActionProp> props)
	{
		List<String> indexStrList = new ArrayList<>();
		props.stream().filter(prop -> prop.getIndex()).forEach(prop -> {
			indexStrList.add(prop.buildIndex(tableName, prop));
		});
		return indexStrList.stream().filter(s -> StringUtils.isNotEmpty(s)).collect(Collectors.toList());
	}

}
